<template>
  <div :style="{ color: color, border: borderStyle }" class="container">
    <div :style="{ color: messageStyle }" class="message">{{ message }}</div>
    <span>{{ indicator.toFixed(accuracy) }}</span>
  </div>
</template>

<script setup>
import { defineProps, ref, watch } from 'vue'

const props = defineProps({
  accuracy: {
    type: Number,
    default: 2
  },
  step: {
    type: Number,
    default: 0.25
  },
  max: {
    type: Number,
    default: 10
  },
  min: {
    type: Number,
    default: 0
  },
  message: {
    type: String,
    default: 'STAB'
  }
})

let interval = null 

const messageStyle = ref('rgb(8, 214, 255)') // 初始颜色
const color = ref('white')
const borderStyle = ref('2px solid white')
const indicator = ref(0)
let runFlag = false

// 监听 indicator 变化
watch(indicator, (newVal, oldVal) => {
  // 可以在这里执行更多的逻辑，如修改消息内容、触发其他状态变化等
  if (props.message == 'STAB' && newVal >= 3 && newVal <= 8) {
    messageStyle.value = 'rgb(155, 255, 134)'
    color.value = 'rgb(155, 255, 134)'
    borderStyle.value = '2px solid rgb(155, 255, 134)'
  } else {
    messageStyle.value = 'rgb(8, 214, 255)'
    color.value = 'white'
    borderStyle.value = '2px solid white'
  }
})

const addAngle = () => {
  if (runFlag) {
    return
  }

  // 清除当前定时器
  if (interval !== null) {
    clearInterval(interval)
    interval = null
  }

  // 判断当前值是否还在允许的范围内，避免超出最大值
  if (indicator.value + props.step <= props.max) {
    interval = setInterval(() => {
      if (indicator.value + props.step <= props.max) {
        indicator.value += props.step
      } else {
        stop() // 达到最大值时停止
      }
    }, 500)
  }
  runFlag = true
}

const minusAngle = () => {
  if (runFlag) {
    return
  }

  // 清除当前定时器
  if (interval !== null) {
    clearInterval(interval)
    interval = null
  }

  // 判断当前值是否还在允许的范围内，避免低于最小值
  if (indicator.value - props.step >= props.min) {
    interval = setInterval(() => {
      if (indicator.value - props.step >= props.min) {
        indicator.value -= props.step
      } else {
        stop() // 达到最小值时停止
      }
    }, 500)
  }
  runFlag = true
}

const stop = () => {
  runFlag = false
  if (interval !== null) {
    clearInterval(interval)
    interval = null
  }
}

defineExpose({
  addAngle,
  minusAngle,
  stop
})
</script>

<style scoped>
.container {
  position: relative;
  z-index: 10;
  width: 70px;
  border-radius: 5px;
  display: flex;
  justify-content: flex-end; /* 将内容对齐到右侧 */
  align-items: center; /* 垂直居中对齐 */
}

.container span {
  margin-right: 15px; /* 添加右边距，微调位置 */
}

.message {
  position: relative;
  top: -30px;
  left: 60px;
  min-width: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 25px;
  font-weight: 600;
  white-space: nowrap; /* 防止换行 */
}
</style>
